# CCNCore::Database::GUI.pm
# Copyright (C) 2006  Stephane Alnet
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 3
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 

# This file is part of the CarrierClass.net project.
# For more information, consult http://carrierclass.net/

package CCNCore::Database::GUI;
use CCN::Database;
use base qw(CCN::Database);
use CCNCore::Home;
use CCNCore::Provision::Base;

sub use_sqlite() { 0 }
# 0 in production
# 1 for demo website (requires sqlite3 file to be manually pre-populated with web.sql)

=pod

    Usage: Provides access to the local GUI (web.sql) database.

    my $local_db = new CCNCore::Provisioning::Local;
    my $gui_db   = new CCNCore::Database::GUI($local_db);
    
=cut

sub initialize
{
    my $self = shift;
    my $local = shift;
    
    $self->die("INTERNAL ERROR") unless defined $local;

    my ($db_cluster,$db_name) = $local->sql_get('SELECT db_cluster, db_name FROM provisioning');

    my @db_servers = $local->sql_get_array('SELECT pk FROM server WHERE db_member = ?',$db_cluster);

    return undef if $#db_servers < 0;

    my $db_server;
    if( grep { $_ eq $local->server_pk } @db_servers )
    {
        $db_server = $local->server_pk;
    }
    else
    {
        $db_server = $db_servers[int(rand($#db_servers+1))];
    }

    my $b = new CCNCore::Provision::Base($local);
    $db_server_ip = $b->get_replication_ip_of($db_server);

    # - compute access tokens (IP, login, password)

    # See db_web.pm for the other side
    my $login = 'www-data';
    
    my $SALT = $local->sql_get(<<'SQL',$db_cluster);
    SELECT salt FROM systems WHERE id = (SELECT the_system FROM cluster WHERE id = ?)
SQL

    my $password = $b->make_password(${SALT},$local->server_pk,"provision");

    my $dsn;

=pod
    if(use_sqlite)
    {
        # This is temporary. Once the schema and code get finalized this will migrate to MySQL or PostgreSQL.
        use DBD::SQLite;
        $dsn = 'dbi:SQLite:dbname='.CCNCore::Home::www.'/data/server/content.sqlite3';
        # /temporary
    }
    else
    {
=cut
        $dsn = qq(DBI:mysql:database=${db_name};host=${db_server_ip}); # ;port=
=pod
    }
=cut

    $self->SUPER::initialize($dsn,$login,$password);
}

1;